<script lang="ts" setup>
import * as realm from '@/api/realm'
import type { RealmTableView } from '@/api/realm/types'
import FormDialog from './compoments/form-dialog.vue'

const queryRequest = reactive<PaginationRequest>({
    pageIndex: 1,
    pageSize: 10,
    order: {
        property: 'id',
        direction: 'DESC'
    }
})
const queryResponse = ref<PaginationResponse<RealmTableView>>({
    total: 0
})

const tableLoading = ref(false)

const query = async () => {
    tableLoading.value = true
    try {
        queryResponse.value = await realm.query(queryRequest)
        console.log(queryResponse)
    } finally {
        tableLoading.value = false
    }
}

watchEffect(() => {
    query()
}, {
    flush: 'post'
})

const formDialogRef = ref()

const remove = async (id: string) => {
    ElMessageBox.confirm('删除的数据不可恢复，确定删除该数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        const result = await realm.remove(id)
        if(result.success){
            ElMessage.success(result.message)
            query()
        } else {
            ElMessage.error(result.message)
        }
    })
}
</script>

<template>
    <el-card>
        <div class="btn-container">
            <el-button type="primary" @click="formDialogRef.open()">添加</el-button>
        </div>
        <div class="table-container">
            <el-table :data="queryResponse?.data" v-loading="tableLoading">
                <el-table-column prop="name" label="应用域" align="center"></el-table-column>
                <el-table-column prop="applications" label="平台数量" align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="formDialogRef.open(row.id)">修改</el-button>
                        <el-button type="primary" link @click="remove(row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pagination-container">
            <el-pagination v-if="queryResponse.total > 0" v-model:page-size="queryRequest.pageSize" v-model:current-page="queryRequest.pageIndex" :total="queryResponse.total"
                layout="total, sizes, prev, pager, next, jumper"></el-pagination>
        </div>
    </el-card>

    <FormDialog ref="formDialogRef" @close="query"></FormDialog>
</template>

<style lang="scss" scoped>
.btn-container {
    text-align: left;
}
.grid-container {
    
}
.pagination-container {
    display: flex;
    margin-top: 15px;

    .el-pagination {
        margin-left: auto;
    }
}
</style>